<template>
  <div>
    <el-card class="box-card">
      <div class="title">
        <h2 class="innerTitle">{{ myPaper.title }}</h2>
        <div class="icons">
          <el-icon v-if="isLike" :size='20' color="red" @click="handleCancelStar"><StarFilled /></el-icon>
          <el-icon v-else :size='20' @click="handleStar"><Star /></el-icon>
          <el-icon v-if="canDownload" :size='20' @click="handleDownload"><Download /></el-icon>
        </div>

      </div>

      <el-row :gutter="20">
        <el-col :span="12">
          <p><strong>DOI:</strong> <a :href="myPaper.doi">{{ myPaper.doi }}</a></p>
          <p><strong>语言:</strong> {{ myPaper.language }}</p>
          <p class="routerTo"><strong>作者:</strong> <span v-for="author in authorList" :key="author.id" @click="toAuthor(author.id)">
            {{ author.display_name }}, </span> </p>

        </el-col>
        <el-col :span="12">
          <p><strong>出版时间:</strong> {{ myPaper.publication_date }}</p>
          <p><strong>类型:</strong> {{ myPaper.type }}</p>
          <p><strong>引用类型:</strong> {{ myPaper.type_crossref }}</p>
        </el-col>
      </el-row>
      <div>
        <strong>关键词：</strong>
      </div>
      <p><span v-for="key in keywordsList" :key="key">
            {{ key }}, </span> </p>
      <div>
        <strong>相关领域：</strong>
      </div>
      <div>
      <p class="routerTo"><span v-for="concept in conceptsList" :key="concept" @click="toConcept(concept.id)">
            {{ concept.display_name }}, </span> </p>
      </div>
      <div>
        <strong>摘要：</strong>
      </div>
      <div class="abstract">
        {{ myPaper.abstract }}
      </div>
    </el-card>
      <div class="myContainer">
        <div class="charts-container">
          <div ref="keywordsChart" class="chart"></div>
          <div ref="conceptsChart" class="chart"></div>
        </div>
        <div class="inner-table">
          <div>
            <strong>引用文献</strong>
          </div>
          <div class="table-container">
            <el-table :data="referenceWorksList" @row-click="handleWXTableClick">
              <el-table-column prop="title" label="标题"/>
              <el-table-column prop="publication_date" label="出版日期" width="300"/>
            </el-table>
          </div>
          <div>
            <strong>相关文献</strong>
          </div>
          <div class="table-container">
            <el-table :data="relatedWorkList" @row-click="handleWXTableClick">
              <el-table-column prop="title" label="标题" />
              <el-table-column prop="publication_date" label="出版日期" width="300" />
            </el-table>
          </div>
        </div>
      </div>
  </div>

</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';
import * as echarts from 'echarts'
import { useRouter } from 'vue-router';
import { req_getWorksInfo,req_addPaperStar,req_askPaperStar, req_removePaperStar, req_getPaperRefList } from '../../../api/index.ts';
import { ElMessage } from 'element-plus';
export default defineComponent({
  name: 'PaperInfo',
  setup() {
    const router = useRouter();  
    const route = router.currentRoute.value;  
    const params = ref('');
    const myPaper = ref({})
    const relatedWorkList = ref([])
    const referenceWorksList = ref([])
    const authorList = ref([])
    const keywordsChart = ref(null);
    const conceptsChart = ref(null);
    const downlUrl = ref('')
    const canDownload = ref(true)
    var isLike = ref(false)
    const keywordsList = ref([])
    const conceptsList = ref([])
    const keywordsShow = ref(false)
    const initVal = () => {
      params.value = route.params.paper_id
      req_getWorksInfo(params.value).then((res)=>{
        myPaper.value = res.data.paper
        myPaper.value.authorships.forEach((item) => {
          authorList.value.push(item.author)
        })
        console.log(authorList.value)
        // myPaper.value.related_works.forEach((item)=>{
        //   relatedWorkList.value.push({'reference':item})
        //   console.log(relatedWorkList)
        // })
        if(myPaper.value.primary_location.pdf_url){
          downlUrl.value = myPaper.value.primary_location.pdf_url
        }else if(myPaper.value.locations[0].pdf_url){
          downlUrl.value = myPaper.value.locations[0].pdf_url
        }else{
          canDownload.value = false
        }
        req_getPaperRefList(myPaper.value.related_works).then((refList) => {
          console.log(refList)
          refList.data.result.forEach((item)=>{
            console.log(item)
            if(item.title){
              relatedWorkList.value.push(item)
            }      
         })
        })
        req_getPaperRefList(myPaper.value.referenced_works).then((refList) => {
          console.log(refList)
          refList.data.result.forEach((item)=>{
            console.log(item)
            if(item.title){
              referenceWorksList.value.push(item)
            }      
         })
        })
        req_askPaperStar(params.value).then((innerRes)=>{
          isLike.value = innerRes.data.result
          console.log(innerRes.data)
        })
        initCharts();
      })
    }
    const handleWXTableClick = (row) => {
      const toWXid = row.id
      router.push({name: 'paper', params: { 'paper_id' : toWXid }})
      setTimeout(() => {
        router.replace('/refresh')
      }, 100);
    }
    const toAuthor = (id) => {
      router.push({name: 'scholar', params: { 'scholar_id' : id }})
    }
    const toConcept = (id) => {
      router.push({name: 'concept', params: { 'concept_id' : id }})
    }
    // ECharts 初始化和配置
    const initCharts = () => {
      const keywordsData = myPaper.value.keywords
      keywordsShow.value = keywordsData.length > 2 ? true : false
      const conceptsData = myPaper.value.concepts
      keywordsList.value = keywordsData.map(item => item.keyword)
      conceptsList.value = conceptsData
      // 初始化关键词柱状图
      if(keywordsShow.value){
        const keywordsChartInstance = echarts.init(keywordsChart.value);
          keywordsChartInstance.setOption({
            title: {
              text: '关键词相关性'
            },
            grid:{
                  left: '14%',
            },
            tooltip: {},
            xAxis: {
              axisLabel: {
                interval : 0,
                rotate : 10
              },
              data: keywordsData.map(item => item.keyword)
            },
            yAxis: {},
            series: [{
              name: 'Score',
              type: 'bar',
              data: keywordsData.map(item => item.score)
            }]
          });
      } else {
        keywordsChart.value.style.display = "none";  
      }
      // 初始化领域柱状图
      const conceptsChartInstance = echarts.init(conceptsChart.value);
      conceptsChartInstance.setOption({
        title: {
          text: '领域相关性'
        },
        grid:{
              left: '14%',
        },
        tooltip: {},
        xAxis: {
          data: conceptsData.map(item => item.display_name),
          axisLabel: {
            interval : 0,
            rotate : 30
          }
        },
        yAxis: {},
        series: [{
          name: 'Score',
          type: 'bar',
          data: conceptsData.map(item => item.score === 0 ? 0.01 : item.score)
        }],
      });
    };
    const handleStar = () => {
      req_addPaperStar(params.value).then((res)=>{
        ElMessage(res.data.msg)
        req_askPaperStar(params.value).then((innerRes)=>{
          isLike.value = innerRes.data.result
          console.log(innerRes.data)
        })
      })
    }
    const handleCancelStar = () => {
      req_removePaperStar(params.value).then((res)=>{
        ElMessage(res.data.msg)
        req_askPaperStar(params.value).then((innerRes)=>{
          isLike.value = innerRes.data.result
          console.log(innerRes.data)
        })
      })
    }
    const handleDownload = () => {
      console.log(downlUrl.value)
      window.open(downlUrl.value);
    }
    // 在组件挂载后初始化图表
    initVal();

    return {
      authorList,
      keywordsChart,
      conceptsChart,
      relatedWorkList,
      referenceWorksList,
      params,
      route,
      myPaper,
      downlUrl,
      isLike,
      conceptsList,
      keywordsList,
      keywordsShow,
      canDownload,
      initVal,
      handleStar,
      handleDownload,
      handleCancelStar,
      handleWXTableClick,
      toAuthor,
      toConcept
    };
  }
});
</script>

<style scoped>
.box-card {
  width: 80vw;
  margin: 30px auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}


h2 {
  font-size: 20px;
  margin-bottom: 15px;
}

a {
  color: #409EFF;
  text-decoration: none;
}

p {
  margin: 10px 0;
  line-height: 1.5;
  color: #606266;
}
.charts-container {
  flex: 1; /* 左侧占 1/3 */
  display: flex;
  flex-direction: column;
}
.chart {
  height: 300px;
}
.myContainer {
  margin:auto;
  display: flex;
  height: 100%; /* 或根据实际需求调整高度 */
  padding-top: 10px;
  width: 80vw;
}
.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.icons :hover {
  cursor: pointer;
}
.abstract {
  text-align: justify;
  text-indent: 2em;
}
.routerTo :hover {
  cursor: pointer;
  color: #409EFF;
}
.inner-table {
  flex: 1; /* 右侧占 2/3 */
}
.table-container {
  display: block;
  overflow-y: scroll;
  height: 300px;
  margin-bottom: 20px;
}
.innerTitle{
  width: 90%;
}
</style>